﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace OfficeLaunch.SharePoint.TwitterMap.Twitter
{
    public class TweetLoader
    {

        public static List<TweetData> GetTweets(string SearchTerm)
        {
            var tweets = new List<TweetData>();

            var queryUrl = string.Format("http://search.twitter.com/search.atom?q={0}", HttpUtility.UrlEncode(SearchTerm));

            var rssReader = new XmlTextReader(queryUrl);
            var rssDocument = new XmlDocument();
            rssDocument.Load(rssReader);

            var manager = new XmlNamespaceManager(rssDocument.NameTable);
            manager.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            manager.AddNamespace("twitter", "http://api.twitter.com/");
            manager.AddNamespace("openSearch", "http://a9.com/-/spec/opensearch/1.1/");
            manager.AddNamespace("google", "http://base.google.com/ns/1.0");

            var entryNodes = rssDocument.SelectNodes("//atom:entry", manager);
            if (entryNodes != null)
            {
                tweets.AddRange(from XmlNode node in entryNodes
                                select new TweetData
                                           {
                                               ID = node.SelectSingleNode("./atom:id", manager).InnerText,
                                               Text = node.SelectSingleNode("./atom:title", manager).InnerText,
                                               Author = node.SelectSingleNode("./atom:author/atom:name", manager).InnerText,
                                               AuthorImageUrl = node.SelectSingleNode("./atom:link[@type='image/png']", manager).Attributes["href"].Value,
                                               Time = DateTime.Parse(node.SelectSingleNode("./atom:updated", manager).InnerText)
                                           });
            }

            return tweets;
        }
    }
}
